<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>入库</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //你要引用的订单类型
        var refOrderTypeTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var refOrderTypeStore = Ext.create('Ext.data.Store', {
          proxy: new Ext.data.HttpProxy({
            url: "/order_type/getAllTypes?sub_type=1"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });
        //要引用的订单类型
        var orderType = Ext.create('Ext.form.ComboBox', {
          store: refOrderTypeStore,
          fieldLabel: '订单类型',
          allowBlank: false,
          blankText: "入库单类型必须选择",
          valueField: 'id',
          displayField: 'name',
          name: 'order_type_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          
          readOnly:false,
          tpl: refOrderTypeTemplate,
          minChars: 0,
          
          
        });
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '90%'
        });
        
        var fromVendor = Ext.create('Ext.form.ComboBox', {
          store: vendorStore,
          fieldLabel: '从供应商',
          allowBlank: false,
          blankText: "供应商必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'vendor_id',          
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          
          minChars: 0
        });
        
        var toWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'warehouse_id',          
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          minChars: 0,
          editable:false          
        });

        //入库日期
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '入库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "入库日期必须选择",
          emptyText: '请选择日期...'
          //anchor: '50%'
        });
        //--------------------------------------------------------------------------
        //入库Grid Store
        var warehousingEntryDS = Ext.create('Ext.data.Store', {
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'description'
            }, {
              name: 'quantity'
            },{
              name: 'product_id'
            },{
              name: 'unit_price'
            }])
        });
        
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productStore,
          fieldLabel: '产品',
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'product_id',
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          }
        });

        productCBB.on('select', function(combo, record, index) {
          var entryRecord = warehousingEntrySM.getSelected();
          if (!entryRecord) {
            return false;
          }
          //Ext.MessageBox.alert("提示",rec.get('number'));
          entryRecord.set('number',records[0].get('number'));
          entryRecord.set('spec',records[0].get('spec'));
          entryRecord.set('unit',records[0].get('unit'));
          entryRecord.set('unit_price',records[0].get('unit_price'));
          entryRecord.set('amount',records[0].get('unit_price'));
          entryRecord.set('quantity',1);
          entryRecord.set('product_id',records[0].get('id'));
        });
        
        
        //生成产品Grid的CM
        var warehousingEntrySM = Ext.create('Ext.selection.CheckboxModel');
        var warehousingEntryCM = Ext.create('Ext.grid.column.Column',[Ext.create('Ext.grid.RowNumberer'),warehousingEntrySM,{
            
            header: 'DB',
            dataIndex: 'id',
            width: 60
          },{
            header: '产品名称',
            dataIndex: 'product_name',
            field: productCBB,
            width: 200
          },{
            header: '产品ID',
            dataIndex: 'product_id',
            width: 50,
            hidden: false
          },{
            header: '产品编号',
            dataIndex: 'number',
            width: 70
          },{
            header: '规格',
            dataIndex: 'spec',
            width: 50
          },{
            header: '单位',
            dataIndex: 'unit',
            width: 50
          },{
            header: '数量',
            align: 'right',
            dataIndex: 'quantity',
            field: Ext.create('Ext.form.field.Number', {
              allowBlank: false,
              allowDecimals: false,
              minValue: 1
            }),
            width: 50
          },{
            header: '金额',
            dataIndex: 'amount',
            align: 'right',
            width: 60
          }
        ]);

        //生成要订单的产品的Grid
        var warehousingEntryGrid = Ext.create('Ext.grid.Panel', {
          store: warehousingEntryDS,
          columns : warehousingEntryCM,
          selModel :warehousingEntrySM,
          width: 800,
          height: 380,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '导入数据',
              iconCls: 'addItem',
              handler : function(){
                
                var Product = warehousingEntryGrid.getStore().recordType;
                var productRecord = new Product({
                  product_name: '请选择产品'
                });
                warehousingEntryDS.insert(0, productRecord);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = warehousingEntrySM.getSelected();
                if (!record) {
                  return false;
                }
                warehousingEntryDS.remove(record);
              }
            }]
        });

        //暂时保存按钮
        var saveButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '入库单详细。',
          iconCls: 'icon-save',
          handler: function(){
            
            //saveWarehousingEntry("save");
            if(entryFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(warehousingEntryDS,rejectKeyArray);
              if (warehousingEntryDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = entryFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/warehousing_entry/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newEntryWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newEntryWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newEntryWin.destroy();
          }
        });
        
        var entryFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '800',
          frame : true,
          url: '/warehousingentry/create',
          method: 'GET',
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [fromVendor]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [orderType]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toWarehouse]
                },{
                  columnWidth: .6,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [warehousingEntryGrid]
                }]
            }],
          buttons: [saveButton,closeButton]
        });
        entryFormPanel.render('entry_form');
        //
        warehousingEntryGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options) {
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          if(obj.field=="quantity"||obj.field=="unit_price"){
            if(obj.record.get('quantity')>0&&obj.record.get('unit_price')){
              obj.record.set('amount',obj.record.get('quantity')*100*obj.record.get('unit_price')/100);
            }
          }
        }
      })
    </script>
  </head>
  <body>
    <div id="entry_form"></div>
  </body>
</html>
